package com.icehand.utils.redis;

import com.icehand.utils.arraylist.ArrayListUtils;
import com.icehand.utils.encryption.MD5Utils;
import com.icehand.utils.map.MapUtils;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;

import static com.icehand.utils.constants.CodeType.UTF8;

/**
 * create by zjm on 2017年8月25日 12:45:14
 */
@Getter
@Setter
public class DefaultRedisCacheKey implements RedisCacheKey {
	private static final Logger LOGGER = LoggerFactory.getLogger(DefaultRedisCacheKey.class);

	private String prefix;
	private String separator = RedisSeparator.COLON;

	@Override
	public String generateKey(String key) {
		return addPrefix(key);
	}

	@Override
	public String generateKey(String[] keys) {
		String cacheKey = ArrayListUtils.join(Arrays.asList(keys),separator);
		return addPrefix(cacheKey);
	}

	@Override
	public String generateKey(Object object) {
		String cacheKey = MD5Utils.encode(object.toString(),UTF8);
		return addPrefix(cacheKey);
	}

	@Override
	public String generateKey(Map<String, Object> map) {
		String cacheKey = MD5Utils.encode(MapUtils.map2Str(map),UTF8);
		return addPrefix(cacheKey);
	}

	private String addPrefix(String key){
		if(StringUtils.isNotEmpty(prefix)){
			key = prefix + separator + key;
		}
		return key;
	}
}
